package com.ef.web.action;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.ConfirmMessage;
import com.ef.constant.ELeadsDealType;
import com.ef.constant.ELeadsStatus;
import com.ef.domain.Leads;
import com.ef.domain.LeadsDealHistory;
import com.ef.domain.School;
import com.ef.util.CustomExample;
import com.ef.util.LeadsExample;

public class VisitAction extends LeadsAction {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("serial")
	public String list() {
		fetchListData();
		String tel = this.getModel().getTelephone();
		if (tel != null && tel.trim().length() > 7) {
			List<Leads> leads = leadsService.findByTelephoneAccurate(tel);
			if (leads.size() == 1) {
				Leads lead = leads.get(0);
				String info = "";
				if (lead.getSchool() == null) {// 没学校
					info = lead.getName();
					if (lead.getLeadsType() != null) {
						info = info + "  " + lead.getLeadsType().toString();
					}
					if (lead.getLeadsStatus() != null) {
						info = info + "  " + lead.getLeadsStatus().toString();
					}
					info = info + " no school , ";
					if (lead.getTm() != null) {
						info = info + " TM " + lead.getTm().getName();
					} else {
						info = info + " no TM";
					}
					;
					if (lead.getCc() != null) {
						info = info + " CC " + lead.getCc().getName();
					} else {
						info = info + " no CC";
					}
					this.resultError(info, "list");
					// System.out.println(info);
					return LIST;
				} else if (!lead.getSchool().getId().equals(
						getSessionUser().getSchool().getId())) {
					info = lead.getName();
					if (lead.getLeadsType() != null) {
						info = info + "  " + lead.getLeadsType().toString();
					}
					if (lead.getLeadsStatus() != null) {
						info = info + "  " + lead.getLeadsStatus().toString();
					}
					info = info + " at school " + lead.getSchool().getName();
					if (lead.getTm() != null) {
						info = info + " TM " + lead.getTm().getName();
					} else {
						info = info + " no TM";
					}
					;
					if (lead.getCc() != null) {
						info = info + " CC " + lead.getCc().getName();
					} else {
						info = info + " no CC";
					}
					this.resultError(info, "list");
					// System.out.println(info);
					return LIST;
				}
			}
		}
		CustomExample<Leads> example = new LeadsExample(this.getModel(),
				Leads.class) {
			public void appendCondition(Criteria criteria) {
				super.appendCondition(criteria);
				criteria.add(Restrictions.isNull("eliteCard"));
				School s = getSessionUser().getSchool();
				if (s != null) {
					criteria.add(Restrictions.eq("school", s));
				}
				criteria.addOrder(Order.desc("showCode"));
			}
		};
		example.addBetweenDateProperty("createTime", selCreateStartTime,
				selCreateEndTime);
		example.addBetweenDateProperty("setApptTime", selSetApptStartTime,
				selSetApptEndTime);
		example.addBetweenDateProperty("showTime", selShowStartTime,
				selShowEndTime);
		example.addBetweenDateProperty("lastEventTime", selLastTouchStartTime,
				selLastTouchEndTime);
		example.addBetweenDateProperty("payTime", selPayStartTime,
				selPayEndTime);
		example.addBetweenDateProperty("tmAssignTime", selAssignTmStartTime,
				selAssignTmEndTime);
		this.listResult = leadsService.findByExample(example, this
				.getStartIndex(), this.getPageSize());
		return LIST;
	};

	public String save() {
		Leads leads = this.getModel();
		leadsService.saveOrUpdate(leads);
		this.setResult(ConfirmMessage.Leads);
		return EDIT;
	}

	private Long selSchoolId;
	
	public Long getSelSchoolId() {
		return selSchoolId;
	}

	public void setSelSchoolId(Long selSchoolId) {
		this.selSchoolId = selSchoolId;
	}

	public String unshow() {

		String showUpComments = getRequest().getParameter("suc2");
		String id = getRequest().getParameter("id");
		if (showUpComments == null || showUpComments.trim().length() == 0) {
			this.resultError("please tell me the reason ", "list");
			return OK;
		}
		Leads leads = leadsService.findById(Long.valueOf(id.trim()));
		leads.setLeadsStatus(ELeadsStatus.CallBack);
		leads.setShowTime(null);
		leads.setShowUpComments(leads.getShowUpComments() + "\n\r("
				+ this.getSessionUser().getName() + " set status to callback)"
				+ showUpComments);
		leadsService.saveOrUpdate(leads);
		LeadsDealHistory dh = new LeadsDealHistory();
		dh.setPreState("showup");
		dh.setCurState("unShowup");
		dh.setDealTime(new Date());
		dh.setOperUser(this.getSessionUser());
		dh.setType(ELeadsDealType.UnShowup);
		dh.setComments(showUpComments);
		dh.setLeads(leads);
		leadsDealHistoryService.saveOrUpdate(dh);

		return OK;
	}

	public String show() {
		Leads leads = this.getModel();
		String showCode = getShowCode();
		leads.setLeadsStatus(ELeadsStatus.ShowUp);
		leads.setShowTime(new Date());
		leads.setShowCode(showCode);
		leadsService.saveOrUpdate(leads);
		return OK;
	}

	/**
	 * 同时出现
	 */
	private String getShowCode() {
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd-HHmmss-SSS");
		return sf.format(new Date());
	}

	public String showAll() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		String showCode = getShowCode();
		String showUpComments = getRequest().getParameter("suc");
		for (String i : id) {
			Leads leads = leadsService.findById(Long.valueOf(i.trim()));
			leads.setShowTime(new Date());
			leads.setShowCode(showCode);
			leads.setShowDealUser(getSessionUser());
			leads.setLeadsStatus(ELeadsStatus.ShowUp);
			String trueshowupcomments = "";
			if (leads.getShowUpComments() == null) {
				trueshowupcomments = "(" + this.getSessionUser().getName()
						+ " show)" + showUpComments;
				leads.setShowUpComments(trueshowupcomments);
			} else {
				trueshowupcomments = leads.getShowUpComments() + "\r\n" + "("
						+ this.getSessionUser().getName() + " show)"
						+ showUpComments;
				leads.setShowUpComments(trueshowupcomments);
			}
			leads.setLastEventCommons(trueshowupcomments);
			leadsService.saveOrUpdate(leads);
			LeadsDealHistory dh = new LeadsDealHistory();
			dh.setDealTime(new Date());
			dh.setOperUser(this.getSessionUser());
			dh.setType(ELeadsDealType.Showup);
			dh.setComments(trueshowupcomments);
			dh.setLeads(leads);
			leadsDealHistoryService.saveOrUpdate(dh);
		}
		return OK;
	}

	public String export() {

		if (selShowStartTime == null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			String start = format.format(new Date());
			try {
				selShowStartTime = format.parse(start + "-01");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (selShowEndTime == null) {
			selShowEndTime = new Date();
		}
		List<Leads> result = null;
		School sch = getSessionUser().getSchool();
		if (sch != null) {
			result = leadsService.findShowUpsBySchool(selShowStartTime,
					selShowEndTime, sch);
		} else {
			result = leadsService.findShowUps(selShowStartTime, selShowEndTime);
		}
		if (result.size() < 1)
			return NONE;
		Map<String, String> map = new LinkedHashMap<String, String>();
		SimpleDateFormat formater = new SimpleDateFormat("MM.dd");
		for (Leads l : result) {
			String st = formater.format(l.getShowTime());
			map.put(st, st);
		}

		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();

		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=showupleads.xls");

		File tempPath = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp"));
		if (!tempPath.exists()) {
			tempPath.mkdirs();
		}
		WritableWorkbook workBook;

		File exportFile = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp/showup.xls"));
		try {
			// TODO styles
			WritableFont font = new WritableFont(WritableFont.TIMES, 12,
					WritableFont.BOLD);
			WritableCellFormat headStyle = new WritableCellFormat(font);
			headStyle.setAlignment(Alignment.CENTRE);
			WritableCellFormat titleStyle = new WritableCellFormat(font);
			titleStyle.setAlignment(Alignment.CENTRE);
			titleStyle.setWrap(false);
			titleStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			WritableFont font_content = new WritableFont(WritableFont.TIMES, 10);
			WritableCellFormat contentStyle = new WritableCellFormat(
					font_content);
			contentStyle.setAlignment(Alignment.CENTRE);
			contentStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentStyle.setWrap(false);
			workBook = Workbook.createWorkbook(exportFile);
			workBook.setProtected(false);

			// create sheets
			WritableSheet activeSheet = null;
			int i = 0;
			for (String s : map.keySet()) {
				activeSheet = workBook.createSheet(s, i);
				i++;
				activeSheet.addCell(new Label(0, 0, s, headStyle));
				activeSheet.mergeCells(0, 0, 9, 0); // 合并一下头部
				activeSheet.addCell(new Label(0, 1, "Name ", titleStyle));
				activeSheet
						.addCell(new Label(1, 1, "       Tel   ", titleStyle));
				activeSheet.addCell(new Label(2, 1, "Source ", titleStyle));
				activeSheet.addCell(new Label(3, 1, "Commnets ", titleStyle));
				activeSheet.addCell(new Label(4, 1, "TM ", titleStyle));
				activeSheet.addCell(new Label(5, 1, "       Show Time    ",
						titleStyle));
				activeSheet.addCell(new Label(6, 1, "        前台签名         ",
						titleStyle));
				activeSheet.addCell(new Label(7, 1, "      CC签名     ",
						titleStyle));
				activeSheet.addCell(new Label(8, 1, "Show Up", titleStyle));
				activeSheet.addCell(new Label(9, 1, "Walk In ", titleStyle));
			}

			int size = result.size();
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			for (int j = 0; j < size; j++) {
				Leads curLeads = result.get(j);
				String showtime = formater.format(curLeads.getShowTime());
				WritableSheet sht = workBook.getSheet(showtime);

				int curRowIndex = sht.getRows();

				sht.addCell(new Label(0, curRowIndex, curLeads.getName(),
						contentStyle));
				sht.addCell(new Label(1, curRowIndex, curLeads
						.getMobileTelephone(), contentStyle));
				sht.addCell(new Label(2, curRowIndex, (curLeads
						.getLeadsSource() == null ? "" : curLeads
						.getLeadsSource().toString()), contentStyle));
				sht.addCell(new Label(3, curRowIndex, curLeads
						.getShowUpComments(), contentStyle));
				if (curLeads.getTm() != null)
					sht.addCell(new Label(4, curRowIndex, curLeads.getTm()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(4, curRowIndex, "", contentStyle));
				sht.addCell(new Label(5, curRowIndex, sdf.format(curLeads
						.getShowTime()), contentStyle));
				if (curLeads.getCr() != null)
					sht.addCell(new Label(6, curRowIndex, curLeads.getCr()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(6, curRowIndex, "", contentStyle));
				if (curLeads.getCc() != null)
					sht.addCell(new Label(7, curRowIndex, curLeads.getCc()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(7, curRowIndex, "", contentStyle));
			}

			workBook.write();
			workBook.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("../../temp/showup.xls");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return NONE;
	}
	
	public String reportPage() {
		fetchListData();
//		CustomExample<Leads> example = new LeadsExample(this.getModel(),
//				Leads.class) {
//			public void appendCondition(Criteria criteria) {
//				super.appendCondition(criteria);
//				criteria.add(Restrictions.isNull("eliteCard"));
//				criteria.add(Restrictions.isNotNull("showTime"));
//				School s = getSessionUser().getSchool();
//				if (s != null) {
//					criteria.add(Restrictions.eq("school", s));
//				}
//				criteria.addOrder(Order.desc("showCode"));
//			}
//		};
//		
//		example.addBetweenDateProperty("showTime", selShowStartTime,
//				selShowEndTime);
//		
//		this.listResult = leadsService.findByExample(example, this
//				.getStartIndex(), this.getPageSize());
		return VIEW;
	};
	
	
	public String exportReport() {
		if (selShowStartTime == null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
			String start = format.format(new Date());
			try {
				selShowStartTime = format.parse(start + "-01");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (selShowEndTime == null) {
			selShowEndTime = new Date();
		}
		List<Leads> result = null;
		School sch =schoolService.findById(selSchoolId);
		if (sch != null) {
			result = leadsService.findShowUpsBySchool(selShowStartTime,
					selShowEndTime, sch);
		} else {
			result = leadsService.findShowUps(selShowStartTime, selShowEndTime);
		}
		if (result.size() < 1)
			return NONE;
		Map<String, String> map = new LinkedHashMap<String, String>();
		SimpleDateFormat formater = new SimpleDateFormat("MM.dd");
		for (Leads l : result) {
			String st = formater.format(l.getShowTime());
			map.put(st, st);
		}

		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();

		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=showupleads.xls");

		File tempPath = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp"));
		if (!tempPath.exists()) {
			tempPath.mkdirs();
		}
		WritableWorkbook workBook;

		File exportFile = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp/showup.xls"));
		try {
			// TODO styles
			WritableFont font = new WritableFont(WritableFont.TIMES, 12,
					WritableFont.BOLD);
			WritableCellFormat headStyle = new WritableCellFormat(font);
			headStyle.setAlignment(Alignment.CENTRE);
			WritableCellFormat titleStyle = new WritableCellFormat(font);
			titleStyle.setAlignment(Alignment.CENTRE);
			titleStyle.setWrap(false);
			titleStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			WritableFont font_content = new WritableFont(WritableFont.TIMES, 10);
			WritableCellFormat contentStyle = new WritableCellFormat(
					font_content);
			contentStyle.setAlignment(Alignment.CENTRE);
			contentStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentStyle.setWrap(false);
			workBook = Workbook.createWorkbook(exportFile);
			workBook.setProtected(false);

			// create sheets
			WritableSheet activeSheet = null;
			int i = 0;
			for (String s : map.keySet()) {
				activeSheet = workBook.createSheet(s, i);
				i++;
				activeSheet.addCell(new Label(0, 0, s, headStyle));
				activeSheet.mergeCells(0, 0, 9, 0); // 合并一下头部
				activeSheet.addCell(new Label(0, 1, "Name ", titleStyle));
				activeSheet
						.addCell(new Label(1, 1, "       Tel   ", titleStyle));
				activeSheet.addCell(new Label(2, 1, "Source ", titleStyle));
				activeSheet.addCell(new Label(3, 1, "Commnets ", titleStyle));
				activeSheet.addCell(new Label(4, 1, "TM ", titleStyle));
				activeSheet.addCell(new Label(5, 1, "       Show Time    ",
						titleStyle));
				activeSheet.addCell(new Label(6, 1, "        前台签名         ",
						titleStyle));
				activeSheet.addCell(new Label(7, 1, "      CC签名     ",
						titleStyle));
				activeSheet.addCell(new Label(8, 1, "Show Up", titleStyle));
				activeSheet.addCell(new Label(9, 1, "Walk In ", titleStyle));
			}

			int size = result.size();
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			for (int j = 0; j < size; j++) {
				Leads curLeads = result.get(j);
				String showtime = formater.format(curLeads.getShowTime());
				WritableSheet sht = workBook.getSheet(showtime);

				int curRowIndex = sht.getRows();

				sht.addCell(new Label(0, curRowIndex, curLeads.getName(),
						contentStyle));
				sht.addCell(new Label(1, curRowIndex, curLeads
						.getMobileTelephone(), contentStyle));
				sht.addCell(new Label(2, curRowIndex, (curLeads
						.getLeadsSource() == null ? "" : curLeads
						.getLeadsSource().toString()), contentStyle));
				sht.addCell(new Label(3, curRowIndex, curLeads
						.getShowUpComments(), contentStyle));
				if (curLeads.getTm() != null)
					sht.addCell(new Label(4, curRowIndex, curLeads.getTm()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(4, curRowIndex, "", contentStyle));
				sht.addCell(new Label(5, curRowIndex, sdf.format(curLeads
						.getShowTime()), contentStyle));
				if (curLeads.getCr() != null)
					sht.addCell(new Label(6, curRowIndex, curLeads.getCr()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(6, curRowIndex, "", contentStyle));
				if (curLeads.getCc() != null)
					sht.addCell(new Label(7, curRowIndex, curLeads.getCc()
							.getName(), contentStyle));
				else
					sht.addCell(new Label(7, curRowIndex, "", contentStyle));
			}

			workBook.write();
			workBook.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("../../temp/showup.xls");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return NONE;
	}
}
